/*
 * Copyright (C) 2010 TopCoder Inc., All Rights Reserved.
 */
package com.hercules.android.receiver.commands.call;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.hercules.android.receiver.Receiver;
import com.hercules.android.receiver.ReceiverUtil;
import com.hercules.android.receiver.commands.XRECommandHandler;
import com.hercules.android.receiver.commands.XRECommandHandlerException;

/**
 * <p>
 * This command handler class will handle the CALL command.
 * </p>
 * 
 * @author TCSASSEMBER
 * @version 1.0
 */
public class XRECallCommandHandler extends XRECommandHandler {
    /**
     * Represents the mapping from method name to the corresponding command
     * handler.
     */
    public Map<String, XRECommandHandler> handlers;

    /**
     * Create a new <code>XRECallCommandHandler</code> with the
     * <code>Receiver</code> and the mapping from method name to the
     * corresponding command handler.
     * 
     * @param receiver
     *            the <code>Receiver</code> instance.
     * @param handlers
     *            the mapping from method name to the corresponding command
     *            handler.
     * @throws IllegalArgumentException
     *             if arguments is null
     */
    public XRECallCommandHandler(Receiver receiver, Map<String, XRECommandHandler> handlers) {
        super(receiver);
        ReceiverUtil.checkNull("handlers", handlers);
        this.handlers = handlers;
    }

    /**
     * Process the CALL command message. It will call the corresponding handler
     * to handle the message based on the method name.
     * 
     * @param message
     *            the command message to be processed.
     * @throws XRECommandHandlerException
     *             if any other error occurs
     */
    public void processCommand(JSONObject message) throws XRECommandHandlerException {
        try {
            String method = message.getString("method");
            if (ReceiverUtil.isEmpty(method)) {
                throw new XRECommandHandlerException("Method can't be empty.");
            }
            // get the corresponding handler
            XRECommandHandler handler = handlers.get(method);
            if (handler == null) {
                return;
                // throw new XRECommandHandlerException("Call method [" + method + "] can't be recognized.");
            }
            handler.processCommand(message);
        } catch (JSONException e) {
            throw new XRECommandHandlerException("Error occurs when reading from json.", e);
        }
    }
}
